<template>
  <div class="content">
    <FilterTable
      ref="packageMaintenanceDLRwxgs"
      :maxHeight="500"
      :columns="columns"
      :dataSource="dataSource"
      :isColumnFilter="false"
      :isSelectColumn="packageType !== 'look'"
      :isToperInfo="false"
      :columnsRef="$route.path + 'packageMaintenanceDLR-wxgs'"
      :onRowSelectChange="selectChange"
      :onCellChange="onCellChange"
      :onSyncTableData="sportTableChangeFun"
      :onColumnsChange="columns => (this.columns = columns)"
    >

    </FilterTable>
    <BaseDialog :visible.sync="visibleSport" title="维修项目选择" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" destroyOnClose>
      <addSport @selectArr="selectSportFun" @closeVin="closeDialog"></addSport>
    </BaseDialog>


  </div>
</template>

<script>
import { state, mutations } from '../store';
import addSport from './addSport.vue';
import { dictionary } from '@/utils/dictMixin';
// import { plusNum ,ownerInvoiceDate,plus} from '@/utils/validate';

export default {
  name: 'wxgs',
  components: {
      addSport,

  },
  props: {

  },
  mixins: [dictionary],
  data() {
    return {
      repairTypeData: '', // 子页面需要的数据
      // addWxgs: false, // 子页面弹框控制
      visibleSport:false,
      data: '',
      dataSource: [],
      columns: this.createTableColumns(),
      // formList: this.createFormList(),
      selectedRows: [],
      disabledType: true,
      totalData: [], // 维修类型和账类下拉数据总和
      accountsLabourPriceList: [],
      showTypeList: false, // 账类说明
      jxxmEditItems: [], // 交修序号
      isDeleted: true, // 删除是否禁用
      orgList: [],
      selectArr:[],
      sportArr:[]
    };
  },
  computed: {
    packageType() {
      return state.packageType;
    },
    packageAllMoney() {
      return state.packageAllMoney;
    },
    packageWxgsList() {
      return state.packageWxgsList;
    },
    packageWxljList() {
      return state.packageWxljList;
    }
  },
  watch: {
    packageWxgsList(newVal) {
      console.log(newVal, 'packageWxgsList==');
      if (this.packageType !== 'add' && !this.dataSource.length) {
        // for (let v of newVal) {
        //   v.labourPrice = v.labourPrice ? v.labourPrice.toFixed(2) : '0.00';
        // }
        this.baseTable.EXECUTE_INSERT(newVal);
        console.log(this.dataSource, 'packageType===SET_COLUMNS_EDITABLE');
      }
    }
  },


  async mounted() {
    console.log(this.packageType, 'mounted==');
    this.baseTable = this.$refs.packageMaintenanceDLRwxgs.$refs.pageTable;
    // const accountsTypeAll = await getVaildAccountTypes();
    // console.log('xxxxx', accountsTypeAll);
    // this.zlList = accountsTypeAll.data.map(x => ({ text: x.chargePartitionName, value: x.chargePartitionCode }));
  },
  beforeDestroy() {},
  methods: {
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '工时代码',
          dataIndex: 'labourCode',
          minWidth: 130
          // sorter: true,
          // showOverflowTooltip: true
        },
        {
          title: '工时名称',
          dataIndex: 'labourName',
          minWidth: 130,
          // sorter: true,
          // showOverflowTooltip: true
          // render: props => {
          //   return <el-input disabled={this.packageType === 'look'} onChange={() => this.labourNameChange()} v-model={props.row.labourName} placeholder='请输入内容'></el-input>;
          // }
        },
        {
          title: '工时id',
          dataIndex: 'labourId',
          hidden: true,
          // showOverflowTooltip: true
        },
        {
          title: '车型',
          dataIndex: 'modelLabourCode',
          hidden: true,
          // showOverflowTooltip: true

        },

        {
          editRequired: true,
          title: '工时数',
          dataIndex: 'stdLabourHour',
          minWidth: 100,
          editable: true,
          editPattern:/^(\d+)(\.?)(\d{0,2})$/,
          initialValue: 0.00,
          render: params => {
            return (
              <el-input
                disabled={this.packageType === 'look'}
                maxlength={8}
                min={0}
                value={params.row.stdLabourHour}

                onChange={e => {
                    if(Number(e)<0){
                        this.$notify.warning({ title: '提示信息', message: '工时数不能小于0!' });
                    }
                    if(e.length>8){
                        this.$notify.warning({ title: '提示信息', message: '长度不能大于5!' });
                    }
                  params.row.stdLabourHour = e;
                  this.handleJhH(params.row);
                  mutations.setPackageWxgsList(this.dataSource);
                }}
                v-model={params.row.stdLabourHour}
              >

              </el-input>
            );
          },
          max:6,
        },
        {
          editRequired: true,
          title: '工时单价',
          dataIndex: 'labourPrice',
          // align: 'right',
          minWidth: 120,
          editable: true,
          precision: 2,
          editType: 'number',
          render: params => {
            const list = this.setLabourPrice(params.row);
            return (
              <el-input
                disabled={this.packageType === 'look'}
                maxlength={8}
                min={0}
                value={params.row.labourPrice}
                onChange={e => {
                   if(Number(e)<0){
                        this.$notify.warning({ title: '提示信息', message: '工时单价不能小于0!' });
                    }
                    if(e.length>8){
                        this.$notify.warning({ title: '提示信息', message: '工时单价长度不能大于5!' });
                    }
                  params.row.labourPrice = e;
                  this.handleJhH(params.row);
                  mutations.setPackageWxgsList(this.dataSource);
                }}
                v-model={params.row.labourPrice}
              >
              </el-input>
            );
          },
          max:9,
        },
        {
          title: '工时费',
          dataIndex: 'labourAmount',
          minWidth: 140,
          precision: 2,
          render: props => {
            console.log('props',props)
            return <span>{(props.row.stdLabourHour * props.row.labourPrice).toFixed(2)}</span>
          }
        },


      ];
    },
    // 行选择
    selectChange(rows) {
      console.log('selectChange-----1111',rows);
      this.selectedRows = rows;
    },
    // 新增{{this.$partsName}}
    add() {
      this.visibleSport = true;
    },
    sportTableChangeFun(val) {
      this.sportArr = val;
      console.log('val---', val);


      let m = 0;
      let j = 0;
      const idTag = false;
      for (const i of val) {
        // m += i.labourAmount ? Number(i.labourAmount) : 0;
         m = m + (i.labourPrice ? Number(i.labourPrice) : 0) * (i.stdLabourHour ? Number(i.stdLabourHour) : 0);

        j += i.manufacturerBonus ? Number(i.manufacturerBonus) : 0;

      }
      if (idTag) {
        mutations.setPackageWxgsList(val);
      }
        mutations.setAllMoney({ gs: m, lj: this.packageAllMoney.lj, fj: this.packageAllMoney.fj,gl: j,fl:this.packageAllMoney.fl, jl:this.packageAllMoney.jl});
    },
    onCellChange(change, row) {
      console.log(change, row, 'change,onCellChange-----');

      const key = Object.keys(change)[0];
      const name = key.substring(key.indexOf('|') + 1);


      if (name === 'labourAmount') {
        console.log(row, 'labourAmount---');
        if (!row.labourAmount) {
          row.labourAmount = 0;
        }
        if (!row.labourPrice) {
          row.labourPrice = 0;
        }
        row.labourAmount = Number(row.labourAmount).toFixed(2);
        row.manufacturerBonus =  row.manufacturerBonus ? row.manufacturerBonus.toFixed(2) : '0.00';
        row.stdLabourHour = row.labourPrice ? (row.labourAmount / row.labourPrice).toFixed(2) : '0.00';//test
        this.handleJhH(row, 4);
      }
      if (name === 'stdLabourHour') {
        console.log(row, 'stdLabourHour---');
        row.stdLabourHour = row.stdLabourHour ? Number(row.stdLabourHour) : 0;
      }

      this.dataSource = [...this.dataSource];
      mutations.setPackageWxgsList(this.dataSource);
      let m = 0;
      if (m !== this.packageAllMoney.gs) {
        mutations.setAllMoney({ gs: m, lj: this.packageAllMoney.lj, fj: this.packageAllMoney.fj ,jl:this.packageAllMoney.jl});
      }
    },
    // 维修工时确认后 rows 是工时选中的数据
    async saveDrawerHandle(rows) {
      console.log(rows, 'saveDrawerHandle---');
      if (!rows) {
        this.visibleSport = false;
        return;
      }
      const data = JSON.parse(JSON.stringify(rows));
      if (data) {
        const codeArr = [];
        for (const i of this.dataSource) {
          if (i.rowKey !== 'D') {
            codeArr.push(i.labourCode);
          }
        }
        for (const x of data) {
          if (codeArr.indexOf(x.labourCode) !== -1) {
            this.$notify.warning({ title: '提示信息', message: '维修工时不能重复添加!' });
            return;
          }
        }
        this.baseTable.EXECUTE_INSERT(data);
        this.visibleSport = false;

      }
    },
    closeDialog() {
      console.log('关闭');
      this.visibleSport = false;
    },

     // 同步表格数据
    onSyncTableData(val) {
      console.log(val, 'onSyncTableData------');
      if (this.packageType === 'look') {
        const arr = [];
        this.columns.forEach(x => {
          if (x.editable) {
            arr.push(x.dataIndex);
          }
        });
        console.log(arr, 'arr===');
        for (const i of val) {
          for (const k of arr) {
            this.baseTable.SET_CELL_DISABLED(i, k, true);
          }
        }
        return;
      }
      let m = 0,
        idTag = false;
      for (const i of val) {
          this.baseTable.SET_CELL_DISABLED(i, 'labourAmount', true);
      }
      if (idTag) {
        mutations.setPackageWxgsList(val);
      }
      if (m !== this.packageAllMoney.gs) {
        mutations.setAllMoney({ gs: m, lj: this.packageAllMoney.lj, fj: this.packageAllMoney.fj,jl:this.packageAllMoney.jl});
      }
    },

    /*添加 活动*/
    selectSportFun(val) {
      this.closeDialog();
      let newArr = [];
      val.forEach((item, index) => {
        var pos = this.sportArr.findIndex((value, index, val) => {
          return value['labourId'] == item['labourId'];
        });
        if (pos == -1) {
          newArr.push(item);
        }
      });
      this.baseTable.EXECUTE_INSERT(newArr);
      this.dataSource = [...this.dataSource];
      console.log(" this.dataSource", this.dataSource)
      mutations.setPackageWxgsList( this.dataSource);
    },

    changeHandle() {},
    handleJhH(x, type) {

      x.stdLabourHour = x.stdLabourHour ? Number(x.stdLabourHour).toFixed(2) : 0;
      x.labourPrice = x.labourPrice ? Number(x.labourPrice).toFixed(2) : 0;
       x.manufacturerBonus = x.manufacturerBonus ? Number(x.manufacturerBonus).toFixed(2) : 0;


      if (type !== 4) {
        x.labourAmount = (x.labourPrice * x.stdLabourHour).toFixed(2);
      }
      console.log(x, 'handleJhH==');
      return;
    },
  setLabourPrice(i) {
      // 设置工时单价
      let list = [];
      const labourPriceList = [],
        labourPriceListOemTag = [];
      for (const k of this.accountsLabourPriceList) {
          for (const m of k.labour) {
              // 厂端+下发
              // labourPrice = m.labourPrice;
              m.labourPrice = m.labourPrice ? Number(m.labourPrice).toFixed(2) : '0.00';
              labourPriceListOemTag.push(m);
              if (!i.labourPrice) {
                i.labourPrice = m.labourPrice;
              }
               list = i.labourPriceList = labourPriceListOemTag;

        }
      }
      return list;
    },
    // 删除按钮
    deleteClick() {
      if (!this.selectedRows.length) {
        this.$notify.warning({ title: '提示信息', message: '请选择要删除的数据！' });
        return;
      }

      for (const i of this.selectedRows) {
        for (const k of this.packageWxljList) {
          if (i.labourId === k.relationLabourId) {
            this.$notify.warning({ title: '提示信息', message: `工时名称 ${i.labourName} 已关联备件，请先取消关联再删除！` });
            return;
          }
        }
      }

      this.baseTable.EXECUTE_DELETE(this.selectedRows);
      this.dataSource = [...this.dataSource];
      mutations.setPackageWxgsList(this.dataSource);
    },

  }
};
</script>

<style lang="less" scoped></style>
